//
//  Helper.m
//  nonghubao
//
//  Created by chongqing642 on 13-1-26.
//  Copyright (c) 2013年 mypocketbaby. All rights reserved.
//

#define MAX_IMAGEDATA_LEN 1000000.0   // max data length 100K

#import "Helper.h"
#import "Config.h"
#import "RegexKitLite.h"
#import "JMFBase.h"
#import "pinyin.h"
#import "Option.h"
#import "DBKit.h"
#import <AddressBook/AddressBook.h>
#import "MoonHTTPRequest.h"
#import "UMFeedbackViewController.h"
#import "Collage.h"

@implementation Helper

//返回一个返回按钮
+ (UIButton *)buttonWithStyle:(ButtonStyle)style
{
    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 48, 39)];

    //返回按钮
    if (style == ButtonStyleNavigationReturn) {
        [button setImage:[UIImage imageNamed:@"com_btn_001_n"] forState:UIControlStateNormal];
    }
    
    //取消按钮
    if (style == ButtonStyleNavigationCancel) {
        [button setImage:[UIImage imageNamed:@"btn_nav_cancel_n"] forState:UIControlStateNormal];
    }
    
    //圈子管理按钮
    if (style == ButtonStyleNavigationCircleList) {
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dynamic_btn_001_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    
    //发布商讯按钮
    if (style == ButtonStyleNavigationWriteMessage) {
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_005_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    
    //添加按钮
    if (style == ButtonStyleNavigationAdd) {
        [button setImage:[UIImage imageNamed:@"com_btn_002_n"] forState:UIControlStateNormal];
    }
    
    //保存按钮
    if (style == ButtonStyleNavigationSave) {
        [button setImage:[UIImage imageNamed:@"com_btn_004_n"] forState:UIControlStateNormal];
    }
    
    //完成按钮
    if (style == ButtonStyleNavigationDone) {
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_003_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    
    //邀请按钮
    if (style == ButtonStyleNavigationInvite) {
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_026_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    
    //编辑按钮
    if (style == ButtonStyleNavigationEdit) {
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_029_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    //管理按钮
    if (style == ButtonStyleNavigationManage) {
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_030_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    
    //管理按钮
    if (style == ButtonStyleNavigationClear) {
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_034_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    //确定按钮
    if (style == ButtonStyleNavigationComfirm) {
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_038_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    //发送按钮
    if (style == ButtonStyleNavigationPost) {
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_039_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    //退出管理
    if (style == ButtonStyleNavigationExitManage) {
        button.frame = CGRectMake(0.0f, 0.0f, 64.0f, 31.0f);
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_031_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    
    //发送
    if (style == ButtonStyleNavigationSend) {
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_039_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    
    //更多，三个点
    if (style == ButtonStyleNavigationMore) {
        [button setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_035_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    }
    
//    if (style == ButtonStyleNavigationDeleteDynamic) {
//        
//    }
    return button;
}

//返回一个文本域
+ (UITextField *)textField:(CGRect)frame byPlaceholder:(NSString *)placeholder
{
    UITextField *textField = [[UITextField alloc] initWithFrame:frame];
    textField.borderStyle = UITextBorderStyleNone;
    textField.autocorrectionType = UITextAutocorrectionTypeYes;
    textField.placeholder = placeholder;
    textField.textAlignment = UITextAlignmentLeft;
    textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    textField.returnKeyType = UIReturnKeyDone;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textField setBackgroundColor:[UIColor whiteColor]];
    
    return textField;
}

// 将日期转化为字符串
+ (NSString *)stringWithDate:(NSDate *)date
{
    // 实例化日期格式化工具
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // 设置日期格式样式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    // 日期转字符串
    NSString *dateString = [dateFormatter stringFromDate:date];
    // 返回转换好的字符串
    return dateString;
}

// 将字符串转化为日期
+ (NSDate *)dateWithString:(NSString *)string
{
    // 实例化日期格式化工具
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // 设置日期格式样式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    // 字符串转换日期
    NSDate *changeDate = [dateFormatter dateFromString:string];
    // 返回转换后日期
    return changeDate;
}


//格式化日期
+ (NSString *)formatDateString:(NSString *)dateString
{
    if (dateString == nil) {
        return @"";
    }
    return [NSString stringWithFormat:@"%@月%@日 %@", [dateString substringWithRange:NSMakeRange(5, 2)], [dateString substringWithRange:NSMakeRange(8, 2)], [dateString substringFromIndex:11]];
}

//格式化日期
+ (NSString *)localizeDateString:(NSString *)dateString
{
    if (dateString == nil) {
        return @"";
    }
    return [NSString stringWithFormat:@"%@年%@月%@日",[dateString substringWithRange:NSMakeRange(0, 4)], [dateString substringWithRange:NSMakeRange(5, 2)], [dateString substringWithRange:NSMakeRange(8, 2)]];
}

+ (CGSize)sizeOfImage:(UIImage *)image forStyle:(PictureStyle)style
{
    CGSize size = image.size;
    
    if (image == nil) {
        return size;
    }
    
    float scale     = 0;   //缩小比率
    float maxWidth  = 0;
    float maxHeight = 0;
    
    //根据样式，设定不同的最大高度和宽度值
    if (style == PictureStyleNormalPreview) {
        maxWidth  = _PICTURE_NORMAL_PREVIEW_WIDTH;
        maxHeight = _PICTURE_NORMAL_PREVIEW_HEIGHT;
    }
    else if (style == PictureStyleNormal) {
        maxWidth = _PICTURE_NORMAL_WIDTH;
        maxHeight = _PICTURE_NORMAL_HEIGHT;
    }
    else if (style == PictureStyleAvartPreview) {
        maxWidth = _PICTURE_AVART_PREVIEW_WIDTH;
        maxHeight = _PICTURE_AVART_PREVIEW_HEIGHT;
    }
    else if (style == PictureStyleAvart) {
        maxWidth = _PICTURE_AVART_WIDTH;
        maxHeight = _PICTURE_AVART_HEIGHT;
    }
    else if (style == PictureStyleFullScreen) {
        maxWidth = _SYS_SCREEN_WIDTH;
        maxHeight = _SYS_SCREEN_HEIGHT;
    }
    else if (style == PictureStyleFullFrame) {
        maxWidth = _SYS_SCREEN_WIDTH;
        maxHeight = _SYS_SCREEN_HEIGHT - 20;
    }
    else if (style == PictureStyleNormalBigPreview) {
        maxWidth = _PICTURE_NORMAL_PREVIEW_BIG_WIDTH;
        maxHeight = _PICTURE_NORMAL_PREVIEW_BIG_HEIGHT;
    }
    else if (style == PictureStyleAnnouncement) {
        maxWidth = _PICTURE_NORMAL_ANNOUNCEMENT_WIDTH;
        maxHeight = _PICTURE_NORMAL_ANNOUNCEMENT_HEIGHT;
    }
    else if (style == PictureStyleCircleMemberAvart) {
        maxWidth = _PICTURE_AVART_CIRCLE_MEMBER_WIDTH;
        maxHeight = _PICTURE_AVART_CIRCLE_MEMBER_HEIGHT;
    }
    //首先处理宽度
    if (image.size.width > maxWidth) {
        //得到缩小比率
        scale = maxWidth / image.size.width;
        size = CGSizeMake(maxWidth, image.size.height * scale);
    }

    //宽度处理后，无论如何再处理一次高度。因为有的图片，宽度符合（或resize）后，高度还是可能超过最大限度
    if (size.height > maxHeight) {
        //得到缩小比率
        scale = maxHeight / size.height;
        size = CGSizeMake(size.width * scale, maxHeight);
    }

    return size;
}

//按比例压缩图片
+ (UIImage *)resizeImage:(UIImage *)image forStyle:(PictureStyle)style
{
    if (image == nil) {
        return nil;
    }

    CGSize size = [self sizeOfImage:image forStyle:style];
    UIImage* newImage = image;

    //
    if (size.width != image.size.width || size.height != image.size.height) {
        //绘制新图
        UIGraphicsBeginImageContext(size);
        [newImage drawInRect:CGRectMake(0, 0, size.width, size.height)];  // scales image to rect
        newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    NSLog(@"image resize as: %f %f -> %f %f", image.size.width, image.size.height, newImage.size.width, newImage.size.height);
    
    return newImage;
}

+ (NSData *)compressImageData:(UIImage *)image withStyle:(PictureStyle)style
{
    
    CGFloat quality;
    
    NSData *data;
    
    if (style == PictureStyleAvart) {
        data = UIImageJPEGRepresentation(image, _PICTURE_QUALITY_AVATAR);
    }
    else {
        data = UIImageJPEGRepresentation(image, _PICTURE_QUALITY_NORMAL);
    }
    
    NSUInteger dataLength = [data length];
    if(dataLength > MAX_IMAGEDATA_LEN)
    {
        quality = 1.0 - MAX_IMAGEDATA_LEN / dataLength;
        data = UIImageJPEGRepresentation(image, quality);
    }
    
    NSLog(@"image compressed as: %u -> %u", UIImageJPEGRepresentation(image, 1).length, data.length);
    
    return data;
}

+ (void)showUTF8String:(NSString *)string
{
    NSLog(@"%@", [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
}

+ (void)showAlertWithTitle:(NSString *)title andMessage:(NSString *)message;
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:_L(@"btn_yes_01") otherButtonTitles:nil, nil];
    
    [alertView show];
}


+ (void)setUserDefaultsWithID:(id)accountID andToken:(NSString *)token andName:(NSString *)name
{
    [[NSUserDefaults standardUserDefaults] setValue:accountID forKey:@"accountID"];
    [[NSUserDefaults standardUserDefaults] setValue:token forKey:@"accountToken"];
    [[NSUserDefaults standardUserDefaults] setValue:name forKey:@"accountName"];
}


+ (BOOL)testNumberWithString:(NSString *)string
{
    BOOL result = [string isMatchedByRegex:@"^[0-9]+(.[0-9]{0,2})?$"];
    
    return result;
}


+ (void)navigationControllerCommonStyle:(UINavigationController *)controller
{
    UIImage* navBgHeader         = [UIImage imageNamed:@"com_bg_001"];           //NavigationVC的背景图片
    controller.navigationBar.titleTextAttributes = _SYS_NAVIGATIONBAR_TITLETEXTATTRIBUTES;    //设定NavigationVC的头部文字样式
    //设定NavigationVC的头部背景
    if (iOS7) {
        [controller.navigationBar setBackgroundImage:navBgHeader forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
    }
    else {
        [controller.navigationBar setBackgroundImage:navBgHeader forBarMetrics:UIBarMetricsDefault];
    }
    
}


//
+ (void)easyShowJMFStatus:(JMFBase *)jmf
{
    if (jmf.message == nil && jmf.data == nil && jmf.error == nil) {

        [self showAlertWithTitle:nil andMessage:_L(@"alert_00")];
    }
    else {

        [self showAlertWithTitle:nil andMessage:[NSString stringWithFormat:@"%@", jmf.message]];
    }
    
    NSLog(@"-- DEBUG Helper.easeShowJMFStatus --\n\n");
    [Helper showUTF8String:jmf.error];
    NSLog(@"%@", jmf.data);
}

// 根据名字拼音查询联系人
+ (NSMutableArray *)filterAddressBook:(NSArray *)localAddressBook withString:(NSString *)string
{
    NSMutableArray* filters = [[NSMutableArray alloc] initWithCapacity:0];
    
    // 循环ugo姓名数组,组装满足查询结果的数组
    for ( int i = 0 ; i < localAddressBook.count; i++) {
        NSMutableDictionary* person = [localAddressBook objectAtIndex:i];
        
        // 汉语姓名各首字母组成的字符串 或 英文姓名全字母组成 字符串
        NSString *letterString = @"";
        
        // 得到当前索引对应联系人姓名
        NSString *zhOrEnName = [[Helper realnameWithPerson:person] stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        // 循环姓名字符串索引位
        for (int j = 0 ; j < [zhOrEnName length] ; j++) {
            // 循环组装 char类型字符串(中文姓名取各首字符拼接,再格式化字符串 英文姓名为全字符拼接,再格式化字符串)
            letterString = [NSString stringWithFormat:@"%@%c",letterString,pinyinFirstLetter([zhOrEnName characterAtIndex:j])];
        }
        
        // 字母模糊匹配
        // (查询输入的是英文字符和实体汉字姓名拼音首字母匹配 或 英文字符和实体英文字母姓名匹配)
        // 如:首字母组合 letterString = sj 查询条件 = sj 实际文本zhOrEnName 包含 时间 的都能查询到
        if ([Helper checkName:letterString includeString:string]) {
            // 加入过滤数组
            [filters addObject:[localAddressBook objectAtIndex:i]];
        }
        // 汉字模糊匹配
        else {
            // (输入的是汉字和实体汉字姓名匹配)
            // 如: zhOrEnName = 时间 查询条件 = 时 满足包含查询条件
            if ([Helper checkName:zhOrEnName includeString:string]) {
                [filters addObject:[localAddressBook objectAtIndex:i]];
            }
        }
    }
    
    return filters;
}

// 获得汉字英文匹配查询结果
// 参数：联系人姓名、查询条件文本
// 返回：bool
// 从通讯录中查询联系人(查询规则是 忽略大小写 和 模糊查询)
+ (BOOL)checkName:(NSString *)name includeString:(NSString *)string
{
    // 字符串查询分解从左到右各参数 (contactName = 姓名)(searchText = 搜索的文本)
    // (NSCaseInsensitiveSearch ＝ 忽略大小写的搜索)(NSMakeRange = 查询范围,从0 到 搜索的文本长度)
	NSComparisonResult result = [name compare:string options:NSCaseInsensitiveSearch range:NSMakeRange(0, string.length)];
    // 字符串contactName 包含 字符串searchText 并忽略大小写
    NSRange rangeString = [name rangeOfString:string options:NSCaseInsensitiveSearch];
    // 采用首字母或首文字 与 搜索的文本 比较方式 (方法比较死)
    // 采用模糊比较方法(方法较好)
	if (result == NSOrderedSame || rangeString.length > 0) {
        return YES;
    } else {
        return NO;
    }
}

+ (NSString *)realnameWithPerson:(NSMutableDictionary *)person
{    
    NSString* realname = [person objectForKey:@"name"];
    
    realname = [realname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    return realname;
}

+ (NSMutableArray *)filterFriendsArray:(NSArray *)friends withString:(NSString *)string
{
    NSMutableArray* filters = [[NSMutableArray alloc] initWithCapacity:0];
    
    // 循环ugo姓名数组,组装满足查询结果的数组
    for ( int i = 0 ; i < friends.count; i++) {
        NSMutableDictionary* friend = [friends objectAtIndex:i];
        
        // 汉语姓名各首字母组成的字符串 或 英文姓名全字母组成 字符串
        NSString *letterString = @"";
        
        // 得到当前索引对应联系人姓名
        NSString *zhOrEnName = [[Helper realnameWithFriend:friend] stringByReplacingOccurrencesOfString:@" " withString:@""];

        // 循环姓名字符串索引位
        for (int j = 0 ; j < [zhOrEnName length] ; j++) {
            // 循环组装 char类型字符串(中文姓名取各首字符拼接,再格式化字符串 英文姓名为全字符拼接,再格式化字符串)
            letterString = [NSString stringWithFormat:@"%@%c",letterString,pinyinFirstLetter([zhOrEnName characterAtIndex:j])];
        }
        
        // 字母模糊匹配
        // (查询输入的是英文字符和实体汉字姓名拼音首字母匹配 或 英文字符和实体英文字母姓名匹配)
        // 如:首字母组合 letterString = sj 查询条件 = sj 实际文本zhOrEnName 包含 时间 的都能查询到
        if ([Helper checkName:letterString includeString:string]) {
            // 加入过滤数组
            [filters addObject:[friends objectAtIndex:i]];
        }
        // 汉字模糊匹配
        else {
            // (输入的是汉字和实体汉字姓名匹配)
            // 如: zhOrEnName = 时间 查询条件 = 时 满足包含查询条件
            if ([Helper checkName:zhOrEnName includeString:string]) {
                [filters addObject:[friends objectAtIndex:i]];
            }
        }
    }
    
    return filters;
}

+ (NSString *)realnameWithFriend:(NSMutableDictionary *)friend
{
    NSString* realname = [friend objectForKey:@"friendRealName"];

    realname = [realname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    return realname;
}

+ (void)showAllTextDialog:(NSString *)message inView:(UIView *)view{
    
    NSArray *windows = [UIApplication sharedApplication].windows;
    
    MBProgressHUD *_HUD = nil;
    
    if (windows.count > 0) {
        
        _HUD = [[MBProgressHUD alloc] initWithView:[windows objectAtIndex:0]];
        [[windows objectAtIndex:0] addSubview:_HUD];
    }else{
        
        _HUD = [[MBProgressHUD alloc] initWithView:view];
        [view addSubview:_HUD];

    }
    
    _HUD.mode = MBProgressHUDModeText;
    
    _HUD.labelText = message;
    
    [_HUD showAnimated:YES whileExecutingBlock:^{
        sleep(2.0f);
    } completionBlock:^{
        [_HUD removeFromSuperview];
    }];
}

+ (void)showAllTextDialog:(NSString *)message inSeconds:(float)seconds
{
    NSArray *windows = [UIApplication sharedApplication].windows;
    MBProgressHUD *_HUD = [[MBProgressHUD alloc] initWithView:[windows objectAtIndex:0]];
    [[windows objectAtIndex:0] addSubview:_HUD];
    
    _HUD.mode = MBProgressHUDModeText;
    _HUD.detailsLabelText = message;
    
    [_HUD showAnimated:YES whileExecutingBlock:^{
        sleep(seconds);
    } completionBlock:^{
        [_HUD removeFromSuperview];
    }];
}

+ (void)logout
{
    //取消之前的设置
    [APService setTags:nil alias:@""];

    [Helper setUserDefaultsWithID:nil andToken:nil andName:nil];
    
    Option* option = [[Option alloc] init];
    option.name = @"accountID";
    option.value = @"";
    [[DBKit sharedDBKit] save:option];
    
    option = [[Option alloc] init];
    option.name = @"accountName";
    option.value = @"";
    [[DBKit sharedDBKit] save:option];
    
    option = [[Option alloc] init];
    option.name = @"accountPassword";
    option.value = @"";
    [[DBKit sharedDBKit] save:option];
    
    option = [[Option alloc] init];
    option.name = @"hadLogout";
    option.value = @"1";
    [[DBKit sharedDBKit] save:option];
    
    //发出通知，使AppDelegate消除Main，并展开Welcome
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Start_Default" object:nil];
}


/*!
 @abstract 验证手机号码是否合法
 */
+ (BOOL)validateMobile:(NSString *)mobile
{
//    //手机号以13， 15，18开头，八个 \d 数字字符
//    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
//    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
//    return [phoneTest evaluateWithObject:mobile];
    
    NSString *mobileStr = [mobile stringByReplacingOccurrencesOfString:@"-" withString:@""];
    mobileStr = [mobileStr stringByReplacingOccurrencesOfString:@"(" withString:@""];
    mobileStr = [mobileStr stringByReplacingOccurrencesOfString:@")" withString:@""];
    mobileStr = [mobileStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *phoneRegex = @"^\\d{11}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobileStr];

}

+ (UIView *)blankViewWithStauts:(NSString *)stauts
{
    UIView *blankView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, _SYS_FRAME_HEIGHT-44.0f)];
    
    blankView.backgroundColor = [UIColor whiteColor];
    
    UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(160.0f-139/4.0f, 150.0f, 139/2.0f, 137/2.0f)];
    icon.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_010@2x" ofType:@"png"]];
    [blankView addSubview:icon];
    
    UILabel *wordsLabel = [[UILabel alloc] initWithFrame:CGRectMake(60.0f, icon.frame.origin.y+icon.frame.size.height+2.0f, 200.0f, [_SYS_FONT_003 lineHeight])];
    wordsLabel.font = _SYS_FONT_003;
    wordsLabel.backgroundColor = [UIColor clearColor];
    wordsLabel.textAlignment = NSTextAlignmentCenter;
    wordsLabel.text = stauts;
    wordsLabel.textColor = [UIColor lightGrayColor];
    [blankView addSubview:wordsLabel];
    
    return blankView;
}

//运行此代码表示，第一次运行APP或者城市数据有更新
+ (void)saveRegionDataToPlist:(NSArray *)regionData withName:(NSString *)name andStandard:(BOOL)standard
{
    if (regionData.count == 0) {
        return;
    }
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filename = [path stringByAppendingPathComponent:name];
    
//    //读文件
//    NSLog(@"%@",filename);
    
    //如果文件不存在
    if([NSDictionary dictionaryWithContentsOfFile:filename] == nil)
    {
        //创建plist文件
        NSFileManager* fm = [NSFileManager defaultManager];
        [fm createFileAtPath:filename contents:nil attributes:nil];
    }
    
    //如果文件存在就要删除，再创建。
    else {
        
        NSFileManager* fm = [NSFileManager defaultManager];
        [fm removeItemAtPath:filename error:nil];
        [fm createFileAtPath:filename contents:nil attributes:nil];
    }
    
    //以下是创建plist代码
    
    //一个省市对象，应该有名称、二级城市列表数组以及所属区域属性
    //一个二级城市对象，应该有名称、三级城市列表数组属性
    //一个三级城市对象，只有名称属性即可
    
    //一级省市数组
    NSMutableArray *states = [NSMutableArray new];
    
    //如果不是标准的，就要加一个“全国”一级城市
    if (!standard) {
        [states addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"全国",@"name", @"", @"area", [NSArray new] ,@"cities",nil]];
    }
    
    for (int i=0; i<regionData.count; i++) {
        
        NSMutableDictionary *state;
        
        //城市的父id等于0表示为一级省市。
        if ([regionData[i][@"parentId"] integerValue] == 0) {
            
            //创建一个一级省市
            state = [NSMutableDictionary new];
            
            //设置一级省市的名称和所属区域
            [state setObject:regionData[i][@"name"] forKey:@"name"];
            [state setObject:regionData[i][@"anArea"] forKey:@"area"];
            
            NSMutableArray *cities = [NSMutableArray new];
            
            //如果不是标准的，就要一级城市的城市子集第一个元素都要有空格
            if (!standard) {
                [cities addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"name",nil]];
            }
            
            //匹配到一个一级省市，就应该去搜索它的二级城市列表
            //由于二级城市列表一定会在一级省市的后面，所以为了优化算法j=i+1
            for (int j=i+1;j<regionData.count; j++) {

                NSMutableDictionary *city;
                
                //如果城市A的父id等于城市B的id，那么就表示城市A是城市B的子城市
                if ([regionData[j][@"parentId"] integerValue] == [regionData[i][@"id"] integerValue]) {
                    
                    city = [NSMutableDictionary new];
                    
                    //设置二级城市的名称
                    [city setObject:regionData[j][@"name"] forKey:@"name"];
                    
                    //匹配到一个二级城市，就应该去搜索它的三级区县
                    //此时会有直辖市这种特殊的情况,haveNode=1表示此城市还有下级城市
                    if ([regionData[j][@"haveNode"] integerValue] == 1) {
                        
                        NSMutableArray *regions = [NSMutableArray new];
                        
                        //如果不是标准的，就要一级城市的城市子集第一个元素都要有空格
                        if (!standard) {
                            [regions addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"name", nil]];
                        }
                        
                        //由于三级区县列表一定会在二级城市的后面，所以为了优化算法k=j+1
                        for (int k=j+1; k<regionData.count; k++) {

                            NSDictionary *region;
                            
                            //如果城市A的父id等于城市B的id，那么就表示城市A是城市B的子城市
                            if ([regionData[k][@"parentId"] integerValue] == [regionData[j][@"id"] integerValue]) {
                                
                                region = [NSDictionary dictionaryWithObjectsAndKeys:regionData[k][@"name"],@"name", nil];
                                
                                [regions addObject:region];
                            }
                        }
                        
                        [city setObject:regions forKey:@"regions"];
                    }
                    
                     [cities addObject:city];
                }
                
            }
            
            //应该将二级城市加入到一级城市的二级城市列表城市中
            [state setObject:cities forKey:@"cities"];
            
            [states addObject:state];
            
        }
    }
    
    [states writeToFile:filename atomically:YES];
}

+ (void)cacheCircleWithIds:(NSMutableArray *)circleIds andNames:(NSMutableArray *)circleNames
{
    [Helper clearCircleCache];
    [[NSUserDefaults standardUserDefaults] setObject:circleIds forKey:@"circleIds"];
    [[NSUserDefaults standardUserDefaults] setObject:circleNames forKey:@"circleNames"];
}

+ (void)clearCircleCache
{
    //暂存选择后的圈子信息
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"circleIds"]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"circleIds"];
    }
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"circleNames"]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"circleNames"];
    }
}

+ (NSString *)encryptPhoneNumber:(NSString *)phone
{
    NSData* mobilesStringData = [phone dataUsingEncoding:NSASCIIStringEncoding];

    return [mobilesStringData base64Encoding];

}

+ (NSString *)decryptCiphertext:(NSString *)ciphertext
{
    NSData* decodeData = [[NSData alloc] initWithBase64Encoding:ciphertext];
    return [[NSString alloc] initWithData:decodeData encoding:NSASCIIStringEncoding];
}

//根据NSUserDefault的phoneBookSynchState判断，是否需要向服务器传递通讯录，并在同步成功后，广播通知。其值：
//=0需要/失败，本方法触发时，检测到这个状态，立即改写为1，然后启动线程同步。AppDelegate会在引导的时候，检查服务器接口状态，可能重置这个值；
//并在启动的时候，发现值=1时认定正在同步的状态是失败的，重置到0，以避免正在同步时，App进程退出，留下的伪状态1。这里有轻微BUG，即=0且AppDelegate异步形式请求服务器接口时，服务器还未返回不需要同步的结果，这时
//本方法被触发了，会启动同步线程。
//=1，有线程正在同步，任何事都不做
//=2，上次线程同步成功，不需要同步了。当同步线程成功完成同步后，设定为此值
+ (void)syncPhoneBook
{
    __block NSArray* addressBookResult;

    //立即更改值，避免其他地方触发
    [[NSUserDefaults standardUserDefaults] setValue:@(1) forKey:@"syncPhoneBookState"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
    //启动线程
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        addressBookResult = [Helper loadContacts];
        NSMutableArray* mobiles = [[NSMutableArray alloc] init];
        
        for (NSDictionary* contacts in addressBookResult) {
            
            for (NSString* mobile in contacts[@"mobiles"]) {
                
                [mobiles addObject:[Helper cleanPhone:mobile]];
            }
        }
        
        NSString* mobilesString = [mobiles componentsJoinedByString:@","];
        
        //encode
        NSData* mobilesStringData = [mobilesString dataUsingEncoding:NSASCIIStringEncoding];
        NSString* encode = [mobilesStringData base64Encoding];
        
        MoonHTTPRequest* request = [[MoonHTTPRequest alloc] initWithURLString:_JSON_URL_U_SYNCPHONEBOOK_ADD];
        [request setParameter:encode forName:@"phoneBook"];
        [request onSuccess:^(id result) {
            
            //同步成功，设定标志，并广播
            if ([result[@"statue"] integerValue] == 1) {
                
                [[NSUserDefaults standardUserDefaults] setValue:@(2) forKey:@"syncPhoneBookState"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"sync_phonebook_state_done" object:nil];
            }
        }];
        [request asynchronous];
    });
}


+ (NSArray *)loadContacts
{
    
    NSMutableArray* contactsArray;
    
    //尝试创建AB的引用。6.0以后要提示授权
    ABAddressBookRef addressBookRef = nil;
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
    {
        addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
        //等待同意后向下执行
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error)
                                                 {
                                                     dispatch_semaphore_signal(sema);
                                                 });
        
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        dispatch_release(sema);
    }
    else
    {
        addressBookRef = ABAddressBookCreate();
    }
    
    CFArrayRef arrayRef = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    NSArray* systemAddressBook = CFBridgingRelease(arrayRef);
    
    if (systemAddressBook.count > 0) {

        //有联系人才产生实例
        contactsArray = [[NSMutableArray alloc] init];
        
        for (int i = 0; i < systemAddressBook.count; i++) {
            
            //装联系人数据的Dict
            NSMutableDictionary* contacts = [[NSMutableDictionary alloc] init];
            
            //转换一个联系人出来
            ABRecordRef recordRef = (__bridge ABRecordRef)[systemAddressBook objectAtIndex:i];//CFBridgingRetain([systemAddressBook objectAtIndex:i]);
            
            // 获取联系人记录id
            NSNumber* sysID = [NSNumber numberWithInt:(ABRecordGetRecordID(recordRef))];
            [contacts setObject:sysID forKey:@"id"];
            
            // 获取联系人记录首名并赋值
            NSString* firstName = CFBridgingRelease(ABRecordCopyValue(recordRef, kABPersonFirstNameProperty));
            if (firstName.length > 0) {
                [contacts setObject:firstName forKey:@"firstName"];
            }
            
            // 获取联系人记录末名并赋值
            NSString* lastName = CFBridgingRelease(ABRecordCopyValue(recordRef, kABPersonLastNameProperty));
            if (lastName.length > 0) {
                [contacts setObject:lastName forKey:@"lastName"];
            }
            
            
            NSMutableArray* mobiles = [[NSMutableArray alloc] init];
            ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(recordRef, kABPersonPhoneProperty);
            if (ABMultiValueGetCount(phoneMulti) != 0) {
                
                for (int k = 0; k < ABMultiValueGetCount(phoneMulti); k++) {

                    CFStringRef numberRef = ABMultiValueCopyValueAtIndex(phoneMulti, k);
                    NSString* mobile = CFBridgingRelease(numberRef);

                    //获得一个联系人的所有电话
                    [mobiles addObject:mobile];
                }
            }
            
            [contacts setObject:mobiles forKey:@"mobiles"];
            [contactsArray addObject:contacts];

            CFRelease(phoneMulti);
            CFRelease(recordRef);
            
        }
    }
    
    return contactsArray;
}


+ (NSString *)cleanPhone:(NSString *)phone
{
    NSString* mobile = [phone stringByReplacingOccurrencesOfString:@"-" withString:@""];
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    mobile = [mobile stringByReplacingOccurrencesOfString:@"(" withString:@""];
    mobile = [mobile stringByReplacingOccurrencesOfString:@")" withString:@""];
    if (mobile.length > 11) {
        
        mobile = [mobile substringWithRange:NSMakeRange(mobile.length - 11, 11)];
    }
    
    return mobile;
}

+ (UINavigationController *)umfeedBackViewController
{
    UMFeedbackViewController *feedbackViewController = [[UMFeedbackViewController alloc] initWithNibName:@"UMFeedbackViewController" bundle:nil];
    feedbackViewController.appkey = _SYS_UMENG_APPKEY;
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:feedbackViewController];
    navigationController.navigationBar.barStyle = UIBarStyleBlack;
    navigationController.navigationBar.translucent = NO;
    
    return navigationController;
}

+ (NSMutableArray *)replaceDictionaryToCollageInResponseData:(NSArray *)data
{
    if (data == nil || data.count == 0) {
        return nil;
    }
    
    NSMutableArray *collageArray = [NSMutableArray new];
    
    for (NSDictionary *dict in data) {
        
        Collage *collage = [Collage new];
        collage.collageId = [dict[@"id"] integerValue];
        collage.name = dict[@"name"];
        collage.region = dict[@"region"];
        [collageArray addObject:collage];
    }
    
    return collageArray;
}

+ (void)saveMobile:(NSString *)mobile
{
    [[NSUserDefaults standardUserDefaults] setObject:mobile forKey:@"mobileHistory"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (UIImage *)imageSuitable:(UIImage *)image
{
//    if (UIImageJPEGRepresentation(image, 1).length > 70000) {
//        return [Helper resizeImage:image forStyle:PictureStyleAvart];
//    }
//    else{
        return image;
//    }
}
@end
